package com.eliza.save.activity

import android.os.Build
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.eliza.library.model.User
import com.eliza.library.tools.InfoTools
import com.eliza.library.tools.file.FileAssetTools
import com.eliza.library.tools.file.SaxHelper
import com.eliza.save.R
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.util.stream.Collectors
import javax.xml.parsers.SAXParser
import javax.xml.parsers.SAXParserFactory


class AssetInfoActivity : AppCompatActivity() {
    private val context = this
    lateinit var fileAssetTools: FileAssetTools

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_analysis)
        fileAssetTools = FileAssetTools(context)
        InfoTools.LogTools(this::class, "fileAssetTools:$fileAssetTools")
        getJson("User.json")
        readxmlForSAX()?.let {
            findViewById<TextView>(R.id.asset_tv_xml).text =
                it.toString()
        }
    }

    fun textFile() {
        try {
            fileAssetTools.getAssetFilesInfo()
            val assets = fileAssetTools.getAssets("User.json")
//            assetFilesInfo.getAssets("/assets/User.json")// java.io.FileNotFoundException: /assets/User.json
        } catch (e: NoSuchFileException) {
            InfoTools.LogTools(this::class.java.name, "${e.message}")
        }

    }

    /**
     * Get json
     * @param jsonFileName json文件全名
     */
    fun getJson(jsonFileName: String) {
        var result = ""
        fileAssetTools.getAssets(jsonFileName).let {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val collect = BufferedReader(InputStreamReader(it)).lines().parallel()
                    .collect(Collectors.joining(System.lineSeparator()))
                result = collect
            }
        }
        /*import org.json.JSONObject */
        val jsonObject = JSONObject(result.toString())
        InfoTools.ToastTools(context, "jsonObject::${jsonObject.getString("name")}")
        /* 将解析后的内容输出到 主页TextView*/
        findViewById<TextView>(R.id.asset_tv_json).text = jsonObject.getString("name")
    }

    //    /home/debi/Code/Android/Ascl/save/src/main/assets/userXml.xml
    @Throws(Exception::class)
    private fun readxmlForSAX(): ArrayList<User?>? {
        //获取文件资源建立输入流对象
        val ips: InputStream = assets.open("userXml.xml")
        //①创建XML解析处理器
        val ss = SaxHelper()
        //②得到SAX解析工厂
        val factory: SAXParserFactory = SAXParserFactory.newInstance()
        //③创建SAX解析器
        val parser: SAXParser = factory.newSAXParser()
        //④将xml解析处理器分配给解析器,对文档进行解析,将事件发送给处理器
        parser.parse(ips, ss)
        ips.close()
        return ss.getUsers()
    }

}